<script setup>
import { ref, onMounted, reactive, watch } from "vue";
import userControl from "../../apis/userControl.js";
import { ElNotification, ElMessage } from "element-plus";
import Filter from "../../components/filter.vue";
import elderlyColumns from "../../utils/elderlyColunms.js";
import { useRouter } from "vue-router";
import { useI18n } from 'vue-i18n';
import * as XLSX from "xlsx";
import { Plus } from '@element-plus/icons-vue';

// 国际化支持
const { t } = useI18n();
const router = useRouter();

// 弹窗状态
const dialogFormVisible = ref(false);

// 查询条件
const option = reactive({
  query: "",
  searchType: ""
});

// 监听查询条件变化
watch(
    () => option.query,
    (newQuery) => {
      if (!newQuery.trim()) {
        fetchData({ query: "", searchType: "" });
      }
    }
);

// 接收搜索条件
const handleSearchOptions = (options) => {
  option.query = options.query;
  option.searchType = options.searchType;
  fetchData(option);
};

// 表格数据
const tableData = ref([]);

// 获取数据
const fetchData = async (res) => {
  try {
    const result = await userControl.search(res);
    // 验证关键字段是否存在
    if (result.length > 0) {
      const sample = result[0];
      // 检查是否有必要的字段
      if (sample.selfCare === undefined) {
        console.warn('数据中缺少 selfCare 字段');
      }
      if (sample.isLivingAlone === undefined) {
        console.warn('数据中缺少 isLivingAlone 字段');
      }
    }
    tableData.value = result;
  } catch (error) {
    ElNotification({
      title: t('error'),
      message: error.message || t('operationFailed'),
      type: "error",
    });
  }
};

// 表单数据
const form = ref({
  elderlyName: "",
  elderlyId: "",
  gender: "",
  contactNumber: "",
  familyContactNumber: "",
  residence: "",
  location: "",
  selfCare: true,
  isLivingAlone: false
});

// 添加老人信息
const addElderly = async () => {
  try {
    await userControl.addElderly(form.value);
    dialogFormVisible.value = false;
    // 添加成功后刷新数据
    fetchData(option);
    // 重置表单
    form.value = {
      elderlyName: "",
      elderlyId: "",
      gender: "",
      contactNumber: "",
      familyContactNumber: "",
      residence: "",
      location: "",
      selfCare: true,
      isLivingAlone: false
    };
    ElNotification({
      title: t('success'),
      message: t('registrationSuccess'),
      type: "success",
    });
  } catch (error) {
    ElNotification({
      title: t('error'),
      message: error.message || t('operationFailed'),
      type: "error",
    });
  }
};

// 打开弹窗
const openDialog = () => {
  dialogFormVisible.value = true;
};

// 行点击事件
const handleRowClick = (row) => {
  const userId = row.elderlyId;
  if (!userId) {
    ElMessage.error(t('userIdNotFound'));
    return;
  }
  router.push({
    name: "person",
    state: { userId }
  });
};

// 下载模板
const downloadTemplate = () => {
  const link = document.createElement("a");
  link.href = "/template.xlsx";
  link.download = "template.xlsx";
  link.click();
};

// 处理文件上传
const handleFileUpload = async (e) => {
  const file = e.target.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = (event) => {
      const data = new Uint8Array(event.target.result);
      const workbook = XLSX.read(data, { type: "array" });
      const firstSheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstSheetName];
      const jsonData = XLSX.utils.sheet_to_json(worksheet);
      registerUsers(jsonData);
    };
    reader.readAsArrayBuffer(file);
  }
};

// 批量注册
const registerUsers = async (users) => {
  try {
    const response = await userControl.registerUsers(users);
    ElNotification({
      title: t('success'),
      message: t('batchRegistrationSuccess'),
      type: "success",
    });
    fetchData(option); // 刷新数据
  } catch (error) {
    console.error("注册失败:", error);
    ElNotification({
      title: t('error'),
      message: error.message || t('batchRegistrationFailed'),
      type: "error",
    });
  }
};

// 初始化加载数据
onMounted(() => {
  fetchData(option);
});
</script>

<template>
  <el-tabs type="border-card">
    <el-tab-pane :label="$t('registration')">
      <div class="button-group">
        <el-button type="primary" @click="downloadTemplate">
          {{ $t('downloadExcelTemplate') }}
        </el-button>
        <el-upload
            :auto-upload="false"
            :show-file-list="false"
            accept=".xlsx,.xls"
            :on-change="handleFileUpload"
        >
          <el-button type="primary">
            {{ $t('selectFile') }}
          </el-button>
        </el-upload>
      </div>
      <div class="filter-container">
        <Filter @sendSearchOptions="handleSearchOptions" />
      </div>
      <!-- 添加按钮 -->
      <div class="icon-container" @click="openDialog">
        <el-icon class="plus-icon">
          <Plus />
        </el-icon>
      </div>
    </el-tab-pane>

    <el-tab-pane :label="$t('query')">
      <div class="filter-container">
        <Filter @sendSearchOptions="handleSearchOptions" />
      </div>
      <div class="table-container">
        <el-table
            :data="tableData"
            style="width: 100%"
            border
            @row-click="handleRowClick"
            v-loading="!tableData.length"
            element-loading-text="$t('loading')"
        >
          <el-table-column
              v-for="(column, index) in elderlyColumns"
              :key="index"
              :label="$t(column.labelKey)"
              :prop="column.props"
              :fixed="column.fixed"
              :min-width="column.minWidth"
              :formatter="column.formatter ? column.formatter(t) : undefined"
          />
        </el-table>
      </div>
    </el-tab-pane>
  </el-tabs>

  <!-- 添加老人信息弹窗 -->
  <el-dialog v-model="dialogFormVisible" :title="$t('addElderlyInfo')" width="600px">
    <el-form :model="form" label-width="120px" :rules="formRules" ref="formRef">
      <el-form-item :label="$t('name')" prop="elderlyName">
        <el-input v-model="form.elderlyName" :placeholder="$t('pleaseEnter') + $t('name')" />
      </el-form-item>
      <el-form-item :label="$t('idNumber')" prop="elderlyId">
        <el-input v-model="form.elderlyId" :placeholder="$t('pleaseEnter') + $t('idNumber')" />
      </el-form-item>
      <el-form-item :label="$t('gender')" prop="gender">
        <el-select v-model="form.gender" :placeholder="$t('pleaseSelect') + $t('gender')">
          <el-option :label="$t('male')" value="男" />
          <el-option :label="$t('female')" value="女" />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('contactNumber')" prop="contactNumber">
        <el-input v-model="form.contactNumber" :placeholder="$t('pleaseEnter') + $t('contactNumber')" />
      </el-form-item>
      <el-form-item :label="$t('familyPhone')" prop="familyContactNumber">
        <el-input v-model="form.familyContactNumber" :placeholder="$t('pleaseEnter') + $t('familyPhone')" />
      </el-form-item>
      <el-form-item :label="$t('residence')" prop="residence">
        <el-input v-model="form.residence" :placeholder="$t('pleaseEnter') + $t('residence')" />
      </el-form-item>
      <el-form-item :label="$t('location')" prop="location">
        <el-input v-model="form.location" :placeholder="$t('pleaseEnter') + $t('location')" />
      </el-form-item>
      <el-form-item :label="$t('selfCareAbility')" prop="selfCare">
        <el-radio-group v-model="form.selfCare">
          <el-radio :label="true">{{ $t('yes') }}</el-radio>
          <el-radio :label="false">{{ $t('no') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('livingAlone')" prop="isLivingAlone">
        <el-radio-group v-model="form.isLivingAlone">
          <el-radio :label="true">{{ $t('yes') }}</el-radio>
          <el-radio :label="false">{{ $t('no') }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('cancel') }}</el-button>
        <el-button type="primary" @click="addElderly">{{ $t('confirm') }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.icon-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #f5f7fa;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin: 20px 0;
}

.plus-icon {
  font-size: 28px;
  color: #409eff;
  transition: transform 0.3s ease, color 0.3s ease;
}

.icon-container:hover {
  background-color: #e6f7ff;
  transform: scale(1.1);
}

.icon-container:hover .plus-icon {
  color: #66b1ff;
}

.icon-container:active {
  transform: scale(0.9);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-input, .el-select, .el-radio-group {
  width: 100%;
  max-width: 400px;
}

.button-group {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.filter-container {
  margin-bottom: 16px;
}

.table-container {
  margin-top: 16px;
}

@media (max-width: 768px) {
  .button-group {
    flex-direction: column;
  }

  .el-input, .el-select {
    width: 100%;
  }
}
</style>
